<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-semibold text-gray-800">报表中心</h2>
      <div class="flex space-x-3">
        <button @click="refreshData" class="flex items-center px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
          <ArrowPathIcon class="h-5 w-5 mr-2" />
          刷新数据
        </button>
        <button @click="exportAllReports" class="flex items-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2">
          <DocumentArrowDownIcon class="h-5 w-5 mr-2" />
          导出全部
        </button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <ChartBarIcon class="h-8 w-8 text-blue-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">设备统计报表</p>
            <p class="text-2xl font-semibold text-gray-900">{{ stats.equipmentReports }}</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <CubeIcon class="h-8 w-8 text-green-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">易耗品报表</p>
            <p class="text-2xl font-semibold text-gray-900">{{ stats.consumableReports }}</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <DocumentTextIcon class="h-8 w-8 text-purple-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">总报表数</p>
            <p class="text-2xl font-semibold text-gray-900">{{ stats.totalReports }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 报表分类 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
      <!-- 设备管理报表 -->
      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-lg font-semibold text-gray-800">设备管理报表</h3>
          <button @click="exportEquipmentReports" class="flex items-center px-3 py-1 bg-blue-100 text-blue-700 rounded-md hover:bg-blue-200 text-sm">
            <DocumentArrowDownIcon class="h-4 w-4 mr-1" />
            导出
          </button>
        </div>
        <div class="space-y-4">
          <div v-for="report in equipmentReports" :key="report.id" class="flex items-center justify-between p-4 border border-gray-200 rounded-lg hover:bg-gray-50">
            <div class="flex items-center">
              <div class="flex-shrink-0">
                <DocumentTextIcon class="h-6 w-6 text-blue-600" />
              </div>
              <div class="ml-3">
                <p class="text-sm font-medium text-gray-900">{{ report.name }}</p>
                <p class="text-xs text-gray-500">{{ report.description }}</p>
              </div>
            </div>
            <div class="flex items-center space-x-2">
              <span class="text-xs text-gray-500">{{ report.lastUpdate }}</span>
              <button @click="viewReport(report)" class="text-blue-600 hover:text-blue-800 text-sm">查看</button>
              <button @click="exportReport(report)" class="text-green-600 hover:text-green-800 text-sm">导出</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 易耗品管理报表 -->
      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-lg font-semibold text-gray-800">易耗品管理报表</h3>
          <button @click="exportConsumableReports" class="flex items-center px-3 py-1 bg-green-100 text-green-700 rounded-md hover:bg-green-200 text-sm">
            <DocumentArrowDownIcon class="h-4 w-4 mr-1" />
            导出
          </button>
        </div>
        <div class="space-y-4">
          <div v-for="report in consumableReports" :key="report.id" class="flex items-center justify-between p-4 border border-gray-200 rounded-lg hover:bg-gray-50">
            <div class="flex items-center">
              <div class="flex-shrink-0">
                <DocumentTextIcon class="h-6 w-6 text-green-600" />
              </div>
              <div class="ml-3">
                <p class="text-sm font-medium text-gray-900">{{ report.name }}</p>
                <p class="text-xs text-gray-500">{{ report.description }}</p>
              </div>
            </div>
            <div class="flex items-center space-x-2">
              <span class="text-xs text-gray-500">{{ report.lastUpdate }}</span>
              <button @click="viewReport(report)" class="text-blue-600 hover:text-blue-800 text-sm">查看</button>
              <button @click="exportReport(report)" class="text-green-600 hover:text-green-800 text-sm">导出</button>
            </div>
          </div>
        </div>
      </div>

    </div>

        <!-- 数据可视化图表 -->
        <div class="mt-8 grid grid-cols-1 lg:grid-cols-2 gap-6">
          <!-- 报表生成趋势 -->
          <div class="bg-white rounded-xl shadow-lg p-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">报表生成趋势</h3>
            <div class="h-80">
              <v-chart 
                class="w-full h-full" 
                :option="reportTrendOption" 
                autoresize
              />
            </div>
          </div>

          <!-- 各类报表占比 -->
          <div class="bg-white rounded-xl shadow-lg p-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">各类报表占比</h3>
            <div class="h-80">
              <v-chart 
                class="w-full h-full" 
                :option="reportPieOption" 
                autoresize
              />
            </div>
          </div>
        </div>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import * as echarts from 'echarts'
import VChart from 'vue-echarts'
import {
  ArrowPathIcon,
  DocumentArrowDownIcon,
  CubeIcon,
  UserGroupIcon,
} from '@heroicons/vue/24/outline'
import request from '@/utils/request'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  PieChart,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 响应式数据
const loading = ref(false)

const stats = reactive({
  equipmentReports: 3,
  consumableReports: 1,
  totalReports: 4
})

// 实际可用的报表数据
const equipmentReports = ref([
  {
    id: 1,
    name: '设备清单报表',
    description: '所有设备的基本信息和状态',
    lastUpdate: '2024-01-20'
  },
  {
    id: 2,
    name: '设备维修记录表',
    description: '设备维修历史及费用统计',
    lastUpdate: '2024-01-19'
  },
  {
    id: 3,
    name: '设备报废统计表',
    description: '报废设备清单及原因分析',
    lastUpdate: '2024-01-18'
  }
])

const consumableReports = ref([
  {
    id: 4,
    name: '易耗品计划报表',
    description: '易耗品采购计划及执行情况',
    lastUpdate: '2024-01-20'
  }
])

// 删除没有数据支持的报表

// 报表生成趋势图配置
const reportTrendOption = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['设备报表', '易耗品报表']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '设备报表',
      type: 'line',
      data: [8, 12, 15, 18, 16, 20, 22, 19, 17, 21, 18, 16],
      smooth: true,
      itemStyle: { color: '#3B82F6' }
    },
    {
      name: '易耗品报表',
      type: 'line',
      data: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
      smooth: true,
      itemStyle: { color: '#10B981' }
    }
  ]
}))

// 各类报表占比饼图配置
const reportPieOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    data: ['设备管理报表', '易耗品管理报表']
  },
  series: [
    {
      name: '报表类型',
      type: 'pie',
      radius: '50%',
      center: ['50%', '50%'],
      data: [
        { value: 3, name: '设备管理报表', itemStyle: { color: '#3B82F6' } },
        { value: 1, name: '易耗品管理报表', itemStyle: { color: '#10B981' } }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
}))

// 方法
const refreshData = async () => {
  try {
    loading.value = true
    
    // 调用统计API获取最新数据
    const [equipmentStats, consumableStats] = await Promise.all([
      request.get('/statistics/equipment'),
      request.get('/statistics/consumable')
    ])
    
    // 更新统计数据
    stats.equipmentReports = equipmentStats.data.totalEquipment || 0
    stats.consumableReports = consumableStats.data.totalPlans || 0
    stats.totalReports = stats.equipmentReports + stats.consumableReports
    
    showMessage('数据刷新成功', 'success')
  } catch (error) {
    showMessage('数据刷新失败', 'error')
  } finally {
    loading.value = false
  }
}

const viewReport = async (report) => {
  try {
    loading.value = true
    showMessage(`正在加载报表：${report.name}`, 'info')
    
    // 根据报表类型调用不同的查看API
    let response
    if (report.id === 1) {
      // 设备清单报表 - 跳转到设备列表页面
      window.open('/equipment', '_blank')
    } else if (report.id === 2) {
      // 设备维修记录表 - 跳转到维修记录页面
      window.open('/equipment-repair', '_blank')
    } else if (report.id === 3) {
      // 设备报废统计表 - 跳转到报废记录页面
      window.open('/equipment-scrap', '_blank')
    } else if (report.id === 4) {
      // 易耗品计划报表 - 跳转到易耗品计划页面
      window.open('/consumable-plan', '_blank')
    } else {
      showMessage('不支持的报表类型', 'error')
      return
    }
    
    showMessage(`报表 "${report.name}" 查看成功`, 'success')
  } catch (error) {
    showMessage(`查看报表 "${report.name}" 失败`, 'error')
    console.error(`查看报表 ${report.name} 失败:`, error)
  } finally {
    loading.value = false
  }
}

const exportReport = async (report) => {
  try {
    loading.value = true
    
    // 根据报表类型调用不同的导出API
    let response
    if (report.id === 1) {
      // 设备清单报表
      response = await request.get('/reports/equipment/export', {
        responseType: 'blob'
      })
    } else if (report.id === 2) {
      // 设备维修记录表
      response = await request.get('/reports/equipment/usage/export', {
        responseType: 'blob'
      })
    } else if (report.id === 3) {
      // 设备报废统计表
      response = await request.get('/reports/equipment/scrap/export', {
        responseType: 'blob'
      })
    } else if (report.id === 4) {
      // 易耗品计划报表
      response = await request.get('/reports/consumable/export', {
        responseType: 'blob'
      })
    } else {
      throw new Error('不支持的报表类型')
    }
    
    // 创建下载链接
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${report.name}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    showMessage(`报表 "${report.name}" 导出成功`, 'success')
  } catch (error) {
    showMessage('报表导出失败', 'error')
  } finally {
    loading.value = false
  }
}

const exportEquipmentReports = async () => {
  try {
    loading.value = true
    
    const response = await request.get('/reports/equipment/export', {
      responseType: 'blob'
    })
    
    // 创建下载链接
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '设备管理报表.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    showMessage('设备管理报表导出成功', 'success')
  } catch (error) {
    showMessage('设备管理报表导出失败', 'error')
  } finally {
    loading.value = false
  }
}

const exportConsumableReports = async () => {
  try {
    loading.value = true
    
    const response = await request.get('/reports/consumable/export', {
      responseType: 'blob'
    })
    
    // 创建下载链接
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '易耗品管理报表.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    showMessage('易耗品管理报表导出成功', 'success')
  } catch (error) {
    showMessage('易耗品管理报表导出失败', 'error')
  } finally {
    loading.value = false
  }
}


const exportAllReports = async () => {
  try {
    loading.value = true
    showMessage('正在导出所有报表，请稍候...', 'info')
    
    // 导出所有可用的报表
    const exportPromises = []
    
    // 设备管理报表
    exportPromises.push(
      request.get('/reports/equipment/export', { responseType: 'blob' }).then(response => {
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = '设备清单报表.xlsx'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        return '设备清单报表'
      })
    )
    
    exportPromises.push(
      request.get('/reports/equipment/usage/export', { responseType: 'blob' }).then(response => {
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = '设备维修记录表.xlsx'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        return '设备维修记录表'
      })
    )
    
    exportPromises.push(
      request.get('/reports/equipment/scrap/export', { responseType: 'blob' }).then(response => {
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = '设备报废统计表.xlsx'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        return '设备报废统计表'
      })
    )
    
    // 易耗品管理报表
    exportPromises.push(
      request.get('/reports/consumable/export', { responseType: 'blob' }).then(response => {
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = '易耗品计划报表.xlsx'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        return '易耗品计划报表'
      })
    )
    
    // 等待所有导出完成
    const results = await Promise.all(exportPromises)
    showMessage(`所有报表导出成功：${results.join('、')}`, 'success')
    
  } catch (error) {
    showMessage('部分报表导出失败', 'error')
    console.error('批量导出报表失败:', error)
  } finally {
    loading.value = false
  }
}


// 简单消息提示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>
